var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        dept:{
            parentName:null,
            parentId:0,
            orderNum:0
        }
    },
    methods: {
        getDept: function(){
            //加载组织树
            $.get(baseURL + "sys/dept/select", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("deptId", vm.dept.parentId);
                if(node != null){
                    ztree.selectNode(node);
                    vm.dept.parentName = node.name;
                }
            })
        },
        add: function(){
            clearValidateFormCache();//清除上一次历史表单验证信息
            var deptId = getDeptIdNomal();
            if(deptId != null){
                vm.showList = false;
                vm.title = "新增";
                vm.dept = {parentName:null,parentId:deptId,orderNum:0};
                vm.getDept();
            }else{
                vm.showList = false;
                vm.title = "新增";
                vm.dept = {parentName:null,parentId:0,orderNum:0};
                vm.getDept();
            }
        },
        update: function () {
            clearValidateFormCache();//清除上一次历史表单验证信息
            var deptId = getDeptId();
            if(deptId == null){
                return ;
            }

            $.get(baseURL + "sys/dept/info/"+deptId, function(r){
                vm.showList = false;
                vm.title = "修改";
                vm.dept = r.dept;

                vm.getDept();
            });
        },
        syn: function(){
            alert("自定义扩展实现!!!");
        },
        del: function () {
            var deptId = getDeptId();
            if(deptId == null){
                return ;
            }

            confirm('确定要删除选中的记录？'  + deptId, function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/dept/delete",
                    data: "deptId=" + deptId,
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.message);
                        }
                    }
                });
            });
        },
        delAll: function () {
            var deptId = getDeptId();
            if(deptId == null){
                return ;
            }

            confirm('强制删除包括当前机构和机构下所有数据？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/dept/deleteAll",
                    data: "deptId=" + deptId,
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.message);
                        }
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            if (! $("#submitForm").valid()) {
                return;
            }
            var url = vm.dept.deptId == null ? "sys/dept/save" : "sys/dept/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.dept),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.message);
                    }
                }
            });
        },
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择组织",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级组织
                    vm.dept.parentId = node[0].deptId;
                    vm.dept.parentName = node[0].name;

                    layer.close(index);
                }
            });
        },
        reload: function () {
            vm.showList = true;
            Dept.table.refresh();
        }
    }
});

var Dept = {
    id: "deptTable",
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
Dept.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '组织ID', field: 'deptId', visible: false, align: 'center', valign: 'middle', width: '150px'},
        {title: '组织名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '500px'},
        {title: '上级组织', field: 'parentName', align: 'center', valign: 'middle', width: '150px'},
        {title: '组织类型', field: 'type', align: 'center', valign: 'middle', sortable: true, width: '150px', formatter: function(value, options, row){
                return value.type == "1" ? '' : '';
        }},
        {title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true}]
    return columns;
};


function getDeptId () {
    var selected = $('#deptTable').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        alert("请选择一条记录");
        return null;
    } else {
        return selected[0].id;
    }
}

function getDeptIdNomal () {
    var selected = $('#deptTable').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        return null;
    } else {
        return selected[0].id;
    }
}


$(function () {
    $.get(baseURL + "sys/dept/info", function(r){
        var colunms = Dept.initColumn();
        var table = new TreeTable(Dept.id, baseURL + "sys/dept/listPage", colunms);
        table.setRootCodeValue(r.deptId);
        table.setExpandColumn(2);
        table.setDefaultParentCode(0);
        table.setIdField("deptId");
        table.setCodeField("deptId");
        table.setNameField("name");
        table.setParentCodeField("parentId");
        table.setExpandAll(true);
        table.setLazyload(true);
        table.setLazyPageSize(10);
        table.init();
        Dept.table = table;
    });
    validateForm();//初始化校验
});

var submitForm_validator = null;
function clearValidateFormCache(){
    submitForm_validator.resetForm();
    $("input").removeData("previousValue");
    $("select").removeData("previousValue");
}
function validateForm() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    submitForm_validator = $('#submitForm').validate({
        rules: {
            name:{
                required: true,
                // remote:{
                //     type:"POST",
                //     url:ctx + "", //请求地址
                //     data:{
                //         serverId: function(){return vm.apiServer.serverId},//增加返回当前对象，用来排除自身
                //         serverCode:function(){ return vm.apiServer.serverCode }
                //     }
                // }
            }
        }, messages: {
            // name:{
            //     remote: icon + "服务器编码已存在"
            // }
        }
    });
}